package com.itheima.employeesys.ui;

import com.itheima.employeesys.bean.Employee;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Random;

public class EmployeeManager extends JFrame {
    private JPanel mainPanel;
    private JPanel topPanel;
    private JTextField searchField;
    private JButton searchButton;
    private JButton addButton;
    private JTable employeeTable;
    private DefaultTableModel tableModel;
    private JPopupMenu popupMenu;
    private JMenuItem editMenuItem;
    private JMenuItem deleteMenuItem;
    private String UserName;
    
    // 员工信息列名
    private String[] columnNames = {"ID", "姓名", "性别", "年龄", "电话", "职位", "入职时间", "薪水", "部门"};
    
    public EmployeeManager(String userName) {
        this.UserName = userName;
        initializeComponents();
        setupLayout();
        setupEventHandlers();
        populateTableData();
        setFrameProperties();
        this.setVisible(true);
    }
    
    private void initializeComponents() {
        mainPanel = new JPanel();
        topPanel = new JPanel();
        
        // 搜索组件
        searchField = new JTextField(20);
        searchButton = new JButton("搜索");
        addButton = new JButton("添加");
        
        // 表格组件
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                // 设置表格不可编辑
                return false;
            }
        };
        employeeTable = new JTable(tableModel);
        employeeTable.setFillsViewportHeight(true);
        employeeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        // 右键菜单
        popupMenu = new JPopupMenu();
        editMenuItem = new JMenuItem("修改");
        deleteMenuItem = new JMenuItem("删除");
        
        // 设置菜单项属性
        editMenuItem.setHorizontalAlignment(SwingConstants.CENTER);
        deleteMenuItem.setHorizontalAlignment(SwingConstants.CENTER);
        
        // 减少菜单项的边距
        editMenuItem.setMargin(new Insets(4, 8, 4, 8));
        deleteMenuItem.setMargin(new Insets(4, 8, 4, 8));
        
        popupMenu.add(editMenuItem);
        popupMenu.add(deleteMenuItem);
    }
    
    private void setupLayout() {
        mainPanel.setLayout(new BorderLayout());
        
        // 顶部面板布局（搜索框、搜索按钮、添加按钮）
        topPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
        topPanel.add(new JLabel("搜索:"));
        topPanel.add(searchField);
        topPanel.add(searchButton);
        topPanel.add(addButton);
        
        // 添加组件到主面板
        mainPanel.add(topPanel, BorderLayout.NORTH);
        mainPanel.add(new JScrollPane(employeeTable), BorderLayout.CENTER);
        
        add(mainPanel);
    }
    
    private void setupEventHandlers() {
        // 添加按钮事件
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 打开添加员工界面
                AddEmployeeUI addEmployeeUI = new AddEmployeeUI(tableModel);
                addEmployeeUI.setVisible(true);
                
                // 监听添加员工窗口关闭事件
                addEmployeeUI.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosed(java.awt.event.WindowEvent windowEvent) {
                        // 获取创建的员工对象并添加到表格中
                        Employee employee = addEmployeeUI.getEmployee();
                        if (employee != null) {
                            Object[] rowData = {
                                employee.getId(),
                                employee.getName(),
                                employee.getGender(),
                                employee.getAge(),
                                employee.getPhone(),
                                employee.getPosition(),
                                employee.getHireDate(),
                                employee.getSalary(),
                                employee.getDepartment()
                            };
                            tableModel.addRow(rowData);
                        }
                    }
                });
            }
        });
        
        // 搜索按钮事件
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                performSearch();
            }
        });
        
        // 搜索框回车键事件
        searchField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                performSearch();
            }
        });
        
        // 表格右键菜单事件
        employeeTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                showPopupMenu(e);
            }
            
            @Override
            public void mouseReleased(MouseEvent e) {
                showPopupMenu(e);
            }
            
            private void showPopupMenu(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    int row = employeeTable.rowAtPoint(e.getPoint());
                    if (row >= 0 && row < employeeTable.getRowCount()) {
                        employeeTable.setRowSelectionInterval(row, row);
                        popupMenu.show(e.getComponent(), e.getX(), e.getY());
                    }
                }
            }
        });
        
        // 修改菜单项事件
        editMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = employeeTable.getSelectedRow();
                if (selectedRow >= 0) {
                    // 获取当前选中行的员工信息
                    String employeeId = (String) tableModel.getValueAt(selectedRow, 0);
                    String name = (String) tableModel.getValueAt(selectedRow, 1);
                    String gender = (String) tableModel.getValueAt(selectedRow, 2);
                    int age = (int) tableModel.getValueAt(selectedRow, 3);
                    String phone = (String) tableModel.getValueAt(selectedRow, 4);
                    String position = (String) tableModel.getValueAt(selectedRow, 5);
                    String hireDate = (String) tableModel.getValueAt(selectedRow, 6);
                    // 修复类型转换问题
                    Object salaryObj = tableModel.getValueAt(selectedRow, 7);
                    double salary = 0.0;
                    if (salaryObj instanceof Double) {
                        salary = (Double) salaryObj;
                    } else if (salaryObj instanceof Integer) {
                        salary = ((Integer) salaryObj).doubleValue();
                    } else {
                        salary = Double.parseDouble(salaryObj.toString());
                    }
                    String department = (String) tableModel.getValueAt(selectedRow, 8);
                    
                    // 创建员工对象
                    Employee employee = new Employee(employeeId, name, gender, age, phone, position, hireDate, salary, department);
                    
                    // 打开添加员工界面进行修改
                    AddEmployeeUI addEmployeeUI = new AddEmployeeUI(tableModel); // 传递tableModel参数
                    addEmployeeUI.setVisible(true);
                    
                    // 设置为修改模式
                    addEmployeeUI.setModifyMode();
                    
                    // 填充当前员工信息到界面
                    addEmployeeUI.setIdFieldText(employeeId);
                    addEmployeeUI.setNameFieldText(name);
                    addEmployeeUI.setGenderComboBoxSelectedItem(gender);
                    addEmployeeUI.setAgeFieldText(String.valueOf(age));
                    addEmployeeUI.setPhoneFieldText(phone);
                    addEmployeeUI.setPositionFieldText(position);
                    addEmployeeUI.setHireDateFieldText(hireDate);
                    addEmployeeUI.setSalaryFieldText(String.valueOf(salary));
                    addEmployeeUI.setDepartmentFieldText(department);
                    
                    // 监听添加员工窗口关闭事件
                    addEmployeeUI.addWindowListener(new java.awt.event.WindowAdapter() {
                        @Override
                        public void windowClosed(java.awt.event.WindowEvent windowEvent) {
                            // 获取修改后的员工对象
                            Employee modifiedEmployee = addEmployeeUI.getEmployee();
                            if (modifiedEmployee != null) {
                                // 删除当前行
                                tableModel.removeRow(selectedRow);
                                // 添加修改后的员工信息
                                Object[] rowData = {
                                    modifiedEmployee.getId(),
                                    modifiedEmployee.getName(),
                                    modifiedEmployee.getGender(),
                                    modifiedEmployee.getAge(),
                                    modifiedEmployee.getPhone(),
                                    modifiedEmployee.getPosition(),
                                    modifiedEmployee.getHireDate(),
                                    modifiedEmployee.getSalary(),
                                    modifiedEmployee.getDepartment()
                                };
                                // 在原来的位置插入修改后的数据
                                tableModel.insertRow(selectedRow, rowData);
                            }
                        }
                    });
                }
            }
        });
        
        // 删除菜单项事件
        deleteMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = employeeTable.getSelectedRow();
                if (selectedRow >= 0) {
                    String employeeId = (String) tableModel.getValueAt(selectedRow, 0);
                    int result = JOptionPane.showConfirmDialog(EmployeeManager.this, 
                            "确定要删除员工ID为 " + employeeId + " 的员工信息吗？", "确认删除", JOptionPane.YES_NO_OPTION);
                    if (result == JOptionPane.YES_OPTION) {
                        tableModel.removeRow(selectedRow);
                    }
                }
            }
        });
    }
    
    // 执行搜索操作
    private void performSearch() {
        String searchId = searchField.getText().trim();
        
        if (searchId.isEmpty()) {
            JOptionPane.showMessageDialog(EmployeeManager.this, "请输入要搜索的员工ID！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        // 遍历表格数据查找匹配的员工ID
        boolean found = false;
        for (int row = 0; row < tableModel.getRowCount(); row++) {
            String employeeId = (String) tableModel.getValueAt(row, 0); // ID在第0列
            if (searchId.equals(employeeId)) {
                // 选中找到的行
                employeeTable.setRowSelectionInterval(row, row);
                // 滚动到选中的行
                employeeTable.scrollRectToVisible(employeeTable.getCellRect(row, 0, true));
                // 获取焦点
                employeeTable.requestFocus();
                
                JOptionPane.showMessageDialog(EmployeeManager.this, "已找到员工，ID: " + employeeId, "搜索结果", JOptionPane.INFORMATION_MESSAGE);
                found = true;
                break;
            }
        }
        
        if (!found) {
            JOptionPane.showMessageDialog(EmployeeManager.this, "未找到ID为 " + searchId + " 的员工！", "搜索结果", JOptionPane.WARNING_MESSAGE);
        }
    }
    
    // 填充表格数据----------------------------------------------------------------------------------------
    private void populateTableData() {
        // 生成20个员工示例数据
        Random random = new Random();
        String[] names = {"张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十", "郑一", "王二", 
                         "冯三", "陈四", "褚五", "卫六", "蒋七", "沈八", "韩九", "杨十", "朱一", "秦二"};
        String[] genders = {"男", "女"};
        String[] positions = {"软件工程师", "产品经理", "设计师", "测试工程师", "运维工程师", "项目经理", "人事专员", "财务专员"};
        String[] departments = {"技术部", "产品部", "设计部", "测试部", "运维部", "管理部", "人事部", "财务部"};
        
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        
        for (int i = 0; i < 20; i++) {
            Object[] rowData = {
                String.format("%04d", i+1), // ID
                names[i], // 姓名
                genders[random.nextInt(genders.length)], // 性别
                22 + random.nextInt(20), // 年龄
                "138" + String.format("%08d", random.nextInt(100000000)), // 电话
                positions[random.nextInt(positions.length)], // 职位
                LocalDate.now().minusDays(random.nextInt(365)).format(formatter), // 入职时间
                (double) (5000 + random.nextInt(10000)), // 薪水 - 确保是double类型
                departments[random.nextInt(departments.length)] // 部门
            };
            tableModel.addRow(rowData);
        }
    }
    
    private void setFrameProperties() {
        setTitle("人事信息管理系统 当前用户:"+UserName);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1000, 600);
        setLocationRelativeTo(null); // 居中显示
        setResizable(true);
    }
    
    public static void main(String[] args) {
        // 设置外观为系统默认外观
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new EmployeeManager("test").setVisible(true);
            }
        });
    }
}